package com.etmay.baseqiniu;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

/**
 *  机房	Zone对象
	华东	Zone.zone0()
	华北	Zone.zone1()
	华南	Zone.zone2()
	北美	Zone.zoneNa0()
	东南亚	Zone.zoneAs0()
 * @author Administrator
 *
 */
public class QiniuManager {
	
	private static final String accessKey = "as6XQeRUSpO5r8R1ieNoAjXLuU0VKKMQrj8Qi7KH";
	private static final String secretKey = "hiC3YSDx65Co8WC6Q7xrS4moXB0ZdHrFxM6UVoUk";
	private static final String bucket = "wlunion";
	private static final String BASE_URL = "http://wlunion.img.crazyduobao.com/";
	
	public static void main(String[] args) {
		String localFilePath = "C:/Users/Administrator/Desktop/icon/icon144.png";
		String imgUrl = uploadFile(localFilePath);
		System.out.println("imgUrl = " + imgUrl);
	}
	
	public static String uploadFile(String fileAbsPath) {
		//构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone2());
		//...其他参数参考类注释
		UploadManager uploadManager = new UploadManager(cfg);
		//...生成上传凭证，然后准备上传
		//如果是Windows情况下，格式是 D:\\qiniu\\test.png
//		String localFilePath = "C:/Users/Administrator/Desktop/icon/icon144.png";
		//默认不指定key的情况下，以文件内容的hash值作为文件名
		String key = null;
//		String key = "icon144.png";
		Auth auth = Auth.create(accessKey, secretKey);
		String upToken = auth.uploadToken(bucket);
		try {
		    Response response = uploadManager.put(fileAbsPath, key, upToken);
		    //解析上传成功的结果
		    DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
		    System.out.println(putRet.key);
		    System.out.println(putRet.hash);
		    return BASE_URL + putRet.key;
		} catch (QiniuException ex) {
		    Response r = ex.response;
		    System.err.println(r.toString());
		    try {
		        System.err.println(r.bodyString());
		    } catch (QiniuException ex2) {
		        //ignore
		    }
		    return null;
		}  
	}
}
